import { queryHome } from "@/api/chkNum";
interface DrawResult {
  draw_type: string;
  is_live: boolean;
  draw_video: string;
}

interface ResItem {
  result: DrawResult;
}

interface HomeParams {
  date: string;
}
type DrawType = "last_draw" | "current_draw" | "next_draw";

const useFetchHome = defineStore("fetch-home", () => {
  const is_live = ref(false);
  const draw_video = ref("");
  const draw_type = ref<DrawType>("current_draw"); // last_draw:上期   next_draw: 下期 current_draw:当期
  const resItem = ref<ResItem | null>(null);
  const homeParams = reactive<HomeParams>({ date: "" });
  const resData = ref<ResItem[]>([]);

  const updateSelectedItem = (type: DrawType) => {
    draw_type.value = type;
    resItem.value =
      resData.value.find(item => item.result.draw_type === type) || null;
    is_live.value = resItem.value?.result?.is_live ?? false;
    draw_video.value = resItem.value?.result?.draw_video ?? "";
    console.log("resItem", resItem.value);
  };

  const setDefaultItem = () => {
    const types: DrawType[] = ["current_draw", "next_draw", "last_draw"];
    for (const type of types) {
      const item = resData.value.find(item => item.result.draw_type === type);
      if (item) {
        updateSelectedItem(type);
        break;
      }
    }
  };

  async function fetchHomeData() {
    try {
      const res = await queryHome(homeParams);
      resData.value = res.data;
      setDefaultItem();
    } catch (error) {
      console.error("Failed to fetch home data:", error);
    }
  }
  function handlePrev() {
    console.log("prev");

    updateSelectedItem("last_draw");
  }

  function handleNext() {
    console.log("next");

    updateSelectedItem("next_draw");
  }

  return {
    resData,
    resItem,
    is_live,
    draw_video,
    draw_type,
    fetchHomeData,
    homeParams,
    handlePrev,
    handleNext
  };
});

export const useFetchHomeRefs = () => storeToRefs(useFetchHome());
export default useFetchHome;
